package loupan_dao

import (
	"bytes"
	"errors"
	"fmt"
	"hft/Database/admin"
	"hft/Database/admin/phone"
	"hft/Http/Models/request"
	"hft/Http/Services/file/file_utils"
	"hft/Http/Services/loupan/loupan_model"
	"hft/Http/Services/loupan/loupan_utils"
	"hft/e"
	"hft/tools"
	"hft/tools/phone/api"
	"hft/tools/phone/model"
	"hft/tools/upload"
	"image/png"
	"regexp"
	"strconv"
	"strings"
	"time"

	"github.com/boombuler/barcode"
	"github.com/boombuler/barcode/qr"
	"gorm.io/gorm"
)

func SelectMaxID(db *gorm.DB) (phone int) {
	var dn uint
	db.Raw("SELECT max(id) FROM `hft_phone_audio`").Scan(&dn)
	return int(dn) + 1
}

func AddPhoneConfigToLouPan(db *gorm.DB, name string, louID uint, managerPhone string, dn int) (err error) {
	var countrySetting *admin.CountrySetting
	db.First(&countrySetting).Limit(1)
	var phoneConfig = phone.PhoneAudio{ID: uint(dn), LouPanName: name, LouID: louID, Broker: fmt.Sprintf(",%v,", managerPhone)}
	if err = db.Create(&phoneConfig).Error; err != nil {
		return errors.New(e.AccountNotExist)
	}
	if err = loupan_utils.Add400PhoneRemote(db, dn, name, managerPhone); err != nil {
		return err
	}
	if err = loupan_utils.AddAudio(fmt.Sprintf("%v", dn), name, db); err != nil {
		fmt.Println(err)
	}
	return nil
}

// 判断账户是否可以在该区域添加楼盘
func CanThisAccountAddLouPanInThisRegion(accountRegionLink string, regionLink string) (err error) {
	if match, err := regexp.MatchString(fmt.Sprintf("(%v)", accountRegionLink), regionLink); err != nil {
		return errors.New(e.ErrorInfo)
	} else if !match {
		return errors.New(e.NoRightToOpera)
	}
	return nil
}

// 处理楼盘的信息
func FindLouPreloadDao(db *gorm.DB, LouPanInfo *request.LouPan) ([]*admin.CommonTag, []*admin.Disadvantage, []*admin.Property, []*admin.RoomType, []*admin.LouPanTeSe) {
	var tags = make([]*admin.CommonTag, 0)
	var dis = make([]*admin.Disadvantage, 0)
	var property = make([]*admin.Property, 0)
	var roomType = make([]*admin.RoomType, 0)
	var tese = make([]*admin.LouPanTeSe, 0)
	if len(LouPanInfo.Tag) != 0 {
		db.Find(&tags, LouPanInfo.Tag)
	}
	if len(LouPanInfo.Disadvantage) != 0 {
		db.Find(&dis, LouPanInfo.Disadvantage)
	}
	if len(LouPanInfo.Tese) != 0 {
		db.Find(&tese, LouPanInfo.Tese)
	}
	if len(LouPanInfo.PropertyUse) != 0 {
		db.Find(&property, LouPanInfo.PropertyUse)
	}
	if len(LouPanInfo.PropertyUse) != 0 {
		db.Find(&roomType, LouPanInfo.RoomType)
	}
	return tags, dis, property, roomType, tese
}

// 替换楼盘信息
func ReplaceLouPreloadDao(db *gorm.DB, louPan *admin.LouPan, tags []*admin.CommonTag, dis []*admin.Disadvantage, property []*admin.Property, roomType []*admin.RoomType, tese []*admin.LouPanTeSe) {
	db.Model(&louPan).Association("Tags").Replace(&tags)
	db.Model(&louPan).Association("Properties").Replace(&property)
	db.Model(&louPan).Association("Disadvantage").Replace(&dis)
	db.Model(&louPan).Association("RoomType").Replace(&roomType)
	db.Model(&louPan).Association("TeSe").Replace(&tese)
}

// 删除分机号
func Delete400Phone(db *gorm.DB, PhoneIDS []uint) (err error) {
	// 先删除手机号
	if len(PhoneIDS) != 0 {
		var dns []string
		for _, v := range PhoneIDS {
			dns = append(dns, fmt.Sprintf("%v", v))
		}
		if code := api.PhoneVirtual.DeletePhone(dns); code != "0" {
			return errors.New(e.Phone400DeleteFail)
		}
		// 删除语音
		var phoneList []*phone.PhoneAudio
		db.Find(&phoneList, PhoneIDS)
		var audioNames []*model.AudioName
		for _, v := range phoneList {
			audioNames = append(audioNames, &model.AudioName{Name: fmt.Sprintf("%v_ani.wav", v.ID)}, &model.AudioName{Name: fmt.Sprintf("%v_dni.wav", v.ID)})
		}
		if res := api.PhoneAudio.DeleteAudio(audioNames); !res {
			// 此处应该扔到定时任务中执行
		}
		if res := db.Unscoped().Delete(&phone.PhoneAudio{}, PhoneIDS); res.RowsAffected == 0 || res.Error != nil {
			return errors.New(e.Phone400DeleteFail)
		}
	}
	return nil
}

// 查找标签
func FindTag(list []*loupan_model.DBLouPan, db *gorm.DB) []*loupan_model.FindLouPanTag {
	var ids []int
	for _, v := range list {
		ids = append(ids, int(v.ID))
	}
	var tags []*loupan_model.FindLouPanTag
	db.
		Select("hft_loupan_tag.`common_tag_id`,hft_loupan_tag.`lou_pan_id`,c.`name`").
		Table("hft_loupan_tag").
		Joins("LEFT JOIN hft_common_tags as c on c.`id` = hft_loupan_tag.`common_tag_id`").
		Where("hft_loupan_tag.`lou_pan_id` in (?)", ids).
		Find(&tags)
	return tags
}

func FindRank(list []*loupan_model.DBLouPan, db *gorm.DB) []*loupan_model.FindRank {
	var ids []int
	for _, v := range list {
		ids = append(ids, int(v.ID))
	}
	var rank []*loupan_model.FindRank
	db.
		Select("hft_loupan_disadvantage.`disadvantage_id`,hft_loupan_disadvantage.`lou_pan_id`,d.`name`,d.`text_color`,d.`cover`").
		Table("hft_loupan_disadvantage").
		Joins("LEFT JOIN hft_disadvantage as d on d.`id` = hft_loupan_disadvantage.`disadvantage_id`").
		Where("hft_loupan_disadvantage.`lou_pan_id` in (?)", ids).
		Unscoped().
		Find(&rank)
	return rank
}

// 创建楼盘二维码
func CreateLouPanQrCode(tx *gorm.DB, lou_id int) (err error) {
	var lou *admin.LouPan
	err = tx.Select("name, id, region_link, name").First(&lou, lou_id).Error
	if err != nil {
		return errors.New(e.LouPanNotExist)
	}
	var strArr = strings.Split(lou.RegionLink, ",")
	var r *admin.Region
	var newArr, _ = strconv.Atoi(strArr[3])
	err = tx.Select("id,pre_fix,manage_id").First(&r, newArr).Error
	if err != nil {
		return errors.New(e.RegionNotFound)
	}
	if r.ManageId == 0 {
		return errors.New(e.NoManagerHere)
	}
	var bucket, _ = upload.NewBucket()
	// ,1,3,72,
	lou_url := fmt.Sprintf("https://m.haofangtiao.com%s/loupan/detail/%d?phone=0", r.PreFix, lou.ID)
	qrCode, _ := qr.Encode(lou_url, qr.M, qr.Auto)
	qrCode, _ = barcode.Scale(qrCode, 256, 256)
	var buf bytes.Buffer
	png.Encode(&buf, qrCode)
	var newFilename = file_utils.GenerateFIleName(fmt.Sprintf("%v%v.png", lou.Name, time.Now().Unix()), tools.GenUUID())
	err = bucket.PutObject(newFilename, bytes.NewReader(buf.Bytes()))
	if err != nil {
		fmt.Println(err)
		return errors.New(e.QrCodeGenFail)
	}
	// 扫码拨号
	lou_url1 := fmt.Sprintf("https://m.haofangtiao.com%s/loupan/detail/%d?phone=1", r.PreFix, lou.ID)
	qrCode1, _ := qr.Encode(lou_url1, qr.M, qr.Auto)
	qrCode1, _ = barcode.Scale(qrCode, 256, 256)
	var buf1 bytes.Buffer
	png.Encode(&buf1, qrCode1)
	var newFilename1 = file_utils.GenerateFIleName(fmt.Sprintf("%v%vphone.png", lou.Name, time.Now().Unix()), tools.GenUUID())
	err = bucket.PutObject(newFilename1, bytes.NewReader(buf1.Bytes()))
	if err != nil {
		fmt.Println(err)
		return errors.New(e.QrCodeGenFail)
	}
	err = tx.Model(&admin.LouPan{}).Where("id = ?", lou.ID).Updates(map[string]interface{}{
		"web_url":        "/" + newFilename,
		"phone_call_url": "/" + newFilename1,
	}).Error
	if err != nil {
		return errors.New(e.ErrorInfo)
	}
	if lou.WebUrl != "" {
		err = upload.NewOss().DeleteFile([]string{lou.WebUrl})
		if err != nil {
			return errors.New(e.DeleteFail)
		}
	}
	if lou.PhoneCallUrl != "" {
		err = upload.NewOss().DeleteFile([]string{lou.PhoneCallUrl})
		if err != nil {
			return errors.New(e.DeleteFail)
		}
	}
	return err
}
